package controllers

import (
	"github.com/astaxie/beego"
	"fmt"
	"encoding/json"
	"beegoProject/models"
	"strconv"
)

type MainController struct {
	beego.Controller
}

func (c *MainController) QueryOne()  {
	var user models.User
	data := c.Ctx.Input.RequestBody
	err := json.Unmarshal(data, &user)
	res, err := models.QueryOne(user.Id)
	if err != nil{
		c.Data["json"] = models.Msg{Code:1, Data:"err"}
	}else {
		c.Data["json"] = models.Msg{Code:0, Data:&res}
	}
	c.ServeJSON()
}

func (c *MainController) Insert()  {
	var user models.User
	data := c.Ctx.Input.RequestBody
	err := json.Unmarshal(data, &user)
	fmt.Println("bbbbbbbbbbbbbbbbbbbbbbbbb", c.Ctx.Input.RequestBody, user)
	if err != nil{
		c.Data["json"] = models.Msg{2, "update error"}
		c.ServeJSON()
		return
	}
	num, err2 := models.Insert(user)
	fmt.Println("tttttttttttt ------ ", num, err2)
	if err2 != nil{
		c.Data["json"] = models.Msg{2, "update error"}
	}else {
		c.Data["json"] = models.Msg{0, "sccuess"}
	}
	c.ServeJSON()
	return
}

func (c *MainController)QueryList()  {
	rows, num, err := models.QuerList()
	if err != nil{
		c.Data["json"] = models.Msg{Code:1, Data:"err"}
	}else {
		c.Data["json"] = models.Msg{Code:0, Data: map[string]interface{}{"total": num, "rows": &rows}}
	}
	c.ServeJSON()
	return
}

func (c *MainController)DeleteOne()  {
	id := c.Ctx.Input.Param(":id")
	idNum, err := strconv.Atoi(id)
	if err != nil{
		c.Data["json"] = models.Msg{Code:1, Data:"err"}
		c.ServeJSON()
		return
	}
	rows, err := models.Delete(idNum)
	fmt.Println("rowssssss --- ", rows)
	if err != nil{
		c.Data["json"] = models.Msg{Code:1, Data:"err"}
	}else {
		c.Data["json"] = models.Msg{Code:0, Data:"success"}
	}
	c.ServeJSON()
	return
}

func (c *MainController)Update()  {
	var user models.User
	data := c.Ctx.Input.RequestBody
	err := json.Unmarshal(data, &user)
	fmt.Println("ccccccccccccccccc", user)
	if err != nil{
		c.Data["json"] = models.Msg{2, "update error"}
		c.ServeJSON()
		return
	}
	num, err2 := models.Update(user)
	fmt.Println("ttttttttttttccccccc ------ ", num, err2)
	if err2 != nil{
		c.Data["json"] = models.Msg{2, "update error"}
	}else {
		c.Data["json"] = models.Msg{0, "sccuess"}
	}
	c.ServeJSON()
	return
}